/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gangcai.mac.shop.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;

import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.base.BaseActivity;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.QiniuBean;
import org.gangcai.mac.shop.bean.UserDataBean;
import org.gangcai.mac.shop.commonutils.ImageLoaderUtils;
import org.gangcai.mac.shop.manager.RetrofitManageres;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.utils.BastiGallery;
import org.gangcai.mac.shop.utils.QiniuUtils;
import org.gangcai.mac.shop.utils.UpLoadImgCallback;
import org.gangcai.mac.shop.utils.UserInfoUtils;

import java.util.ArrayList;
import java.util.List;

import org.gangcai.mac.shop.R;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static org.gangcai.mac.shop.constants.Constant.CODE_SUCC;

/**
 * register screen
 */
public class RegisterNicknameActivity extends BaseActivity {
    private static final String TAG = "RNickActivity";
    private EditText userNickEditText;
    private Button registernickBtn;
    private String userNickName;
    private String userAvatarString;
    ImageView userAvatarImage;
    private int REQUEST_CODE = 120;
    private String uidString;

    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            ImageLoaderUtils.display( context, imageView, path );
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.em_activity_register_nickname );
        uidString = SPUtils.getInstance().getString( "uid", "0" );
        userAvatarImage = (ImageView) findViewById( R.id.userAvatarImage );
        userNickEditText = (EditText) findViewById( R.id.usernick );
        registernickBtn = (Button) findViewById( R.id.registernickBtn );
        userAvatarImage.setOnClickListener( view -> {
            ImgSelConfig config = new ImgSelConfig.Builder( loader )
                    // 是否多选
                    .multiSelect( true )
                    // 确定按钮背景色
                    .btnBgColor( Color.TRANSPARENT )
                    .titleBgColor( ContextCompat.getColor( RegisterNicknameActivity.this, R.color.main_color ) )
                    // 使用沉浸式状态栏
                    .statusBarColor( ContextCompat.getColor( RegisterNicknameActivity.this, R.color.main_color ) )
                    // 返回图标ResId
                    .backResId( R.drawable.ic_arrow_back )
                    .title( "图片" )
                    // 第一个是否显示相机
                    .needCamera( true )
                    // 最大选择图片数量
                    .maxNum( 1 )
                    .build();
            ImgSelActivity.startActivity( this, config, REQUEST_CODE );
        } );
        userNickName = UserInfoUtils.getNickName( RegisterNicknameActivity.this );
        userAvatarString = UserInfoUtils.getAppUserUrl( RegisterNicknameActivity.this );
        if (userAvatarString.length() > 5) {
            userNickEditText.setText( userNickName );
            registernickBtn.setText( "设置资料" );
            userAvatarImage.setImageResource( R.drawable.personal_icon_default_avatar );
            Log.d( "getImageAvatarString", userAvatarString );
            if (userAvatarString.length() > 32) {
                Glide.with( RegisterNicknameActivity.this ).load( userAvatarString ).into( userAvatarImage );
            }
        }
    }


    private void upLoadFeedBackImg(byte[] img) {
        final ProgressDialog pd = new ProgressDialog( RegisterNicknameActivity.this );
        pd.setCanceledOnTouchOutside( false );
        pd.setOnCancelListener( new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d( TAG, "EMClient.getInstance().onCancel" );
            }
        } );
        pd.setMessage( "正在上传" );
        pd.show();
        QiniuUtils.getUploadManagerInstance();
        //已经上传过的不上传
        QiniuUtils.uploadImg( this, img, QiniuUtils.createImageKey( UserInfoUtils.getPhone( this ) ), new UpLoadImgCallback() {
            @Override
            public void onSuccess(String imgUrl) {
                pd.dismiss();
                Log.e( "111111111111", "imgUrl = " + imgUrl );
                userAvatarString = imgUrl;
                Glide.with( RegisterNicknameActivity.this ).load( imgUrl ).into( userAvatarImage );
            }

            @Override
            public void onFailure() {
                pd.dismiss();
            }
        } );
    }

    public void register(View view) {
        final String usernick = userNickEditText.getText().toString().trim();
        if (TextUtils.isEmpty( usernick )) {
            Toast.makeText( this, getResources().getString( R.string.User_name_cannot_be_empty ), Toast.LENGTH_SHORT ).show();
            userNickEditText.requestFocus();
            return;
        }
        if (TextUtils.isEmpty( userAvatarString )) {
            Toast.makeText( this, "请选择您的用户头像", Toast.LENGTH_SHORT ).show();
            return;
        }

        if (!TextUtils.isEmpty( usernick )) {
            final ProgressDialog pd = new ProgressDialog( this );
//            if (userNickName != null && userAvatarString != null) {
            pd.setMessage( "正在处理，请稍后..." );
            pd.show();
            RetrofitManageres.getInstance()
                    .create( AppAPI.class )
                    .UpdaateNickName( uidString, usernick, userAvatarString )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribeOn( Schedulers.io() )
                    .subscribe( new CommonObserver<CommonResonseBean>() {
                        @Override
                        public void onSuccess(CommonResonseBean value) {
                            if (value.getCode() == CODE_SUCC) {
                                UserInfoUtils.setNikeName( usernick, RegisterNicknameActivity.this );
                                UserInfoUtils.setAppUserUrl( userAvatarString, RegisterNicknameActivity.this );
                                Toast.makeText( RegisterNicknameActivity.this, "修改个人资料成功", Toast.LENGTH_SHORT ).show();
                                finish();
                            } else {
                                Toast.makeText( RegisterNicknameActivity.this, "修改个人资料失败，请稍后再试", Toast.LENGTH_SHORT ).show();
                            }
                            pd.dismiss();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError( e );
                            Toast.makeText( RegisterNicknameActivity.this, "修改个人资料失败，请稍后再试", Toast.LENGTH_SHORT ).show();
                            pd.dismiss();
                        }
                    } );

//            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra( ImgSelActivity.INTENT_RESULT );
            if (pathList.size() > 0) {
                String fileName = pathList.get( 0 );
                ImageLoaderUtils.display( RegisterNicknameActivity.this, userAvatarImage, pathList.get( 0 ) );
                byte[] img = BastiGallery.Bitmap2Bytes( BastiGallery.getimage( fileName ) );
                upLoadFeedBackImg( img );
            }

        }
    }

    public void back(View view) {
        finish();
    }

}
